package com.jgy.book;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @author 姜光远
 * @date 2023/7/21 15:58
 */
public class Commonutils {

    Map map = new HashMap();


    //private static final Lexicon dictionary = "111";

    // try-finally - No longer the best way to close resources!
    static String firstLineOfFile1(String path) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        }catch (Exception e){
            return null;
        }
    }



    // try-with-resources - the the best way to close resources!
    static String firstLineOfFile2(String path) throws IOException {
        try (BufferedReader br = new BufferedReader(
                new FileReader(path))) {
            return br.readLine();
        }
    }

    // try-finally is ugly when used with more than one resource!
    static void copy1(String src, String dst) throws IOException {
        InputStream in = Files.newInputStream(Paths.get(src));
        try {
            OutputStream out = Files.newOutputStream(Paths.get(dst));
            try {
                byte[] buf = new byte[BUFFER_SIZE];
                int n;
                while ((n = in.read(buf)) >= 0) {
                    out.write(buf, 0, n);
                }
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }


    // try-with-resources on multiple resources - short and sweet
    static void copy2(String src, String dst) throws IOException {
        try (InputStream in = Files.newInputStream(Paths.get(src));
             OutputStream out = Files.newOutputStream(Paths.get(dst))) {
            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = in.read(buf)) >= 0) {
                out.write(buf, 0, n);
            }
        }
    }


}
